import { getSbData, supabase } from "../../utils/supabase";

function uniLogin() {
  return new Promise((success, fail) => {
    uni.login({
      success,
      fail,
    });
  });
}

export default {
  actions: {
    async mpLogin({ dispatch, rootState }) {
      let usrData = {};
      // #ifdef H5
      const res2 = await supabase.auth.getSession();
      usrData = res2.data?.session || {};
      // #endif

      // #ifdef MP
      const { code } = await uniLogin();
      const res = await supabase.auth.signInWithWechat({
        code,
      });
      const data = getSbData(res);
      usrData = data.session;
      await dispatch("setStore", {
        usrData,
      });
      // #endif
      // console.log({ usrData });
      if (usrData.access_token) {
        await dispatch("getUserInfo");
      }
      return usrData;
    },
    async getUserInfo({ dispatch }) {
      const res = await supabase.auth.getUser();
      const { user } = getSbData(res);
      console.log(1, user);
      return dispatch("setStore", {
        userInfo: user,
      });
    },
    async postUserInfo({ dispatch }, data) {
      const res = await supabase.auth.updateUser({
        data,
      });
      const { user } = getSbData(res);
      // console.log(2, user);
      await dispatch("setStore", {
        userInfo: user,
      });
      await uni.$api.post("/bot/auth/user-info", data);
      return user;
    },
  },
};
